<?php
declare(strict_types=1);

namespace SixShop\AliyunWuliu\Entity;

use SixShop\AliyunWuliu\Extension;
use SixShop\AliyunWuliu\Facade\WuLiuClient;
use SixShop\Core\Contracts\LogisticsInformationResponse;
use SixShop\Core\Contracts\LogisticsInterface;
use SixShop\Core\Entity\BaseEntity;
use think\facade\Cache;
use think\Model;
use function SixShop\Core\throw_logic_exception;

class ExtensionWuLiuEntity extends BaseEntity
{
    public function getWuliuInfo(int $userID, string $no, string $type = ''): array
    {
        $entity = $this->where('number', $no)->when($type, function (Model $query, $type) {
            $query->where('type', $type);
        })->findOrEmpty();
        if (!$entity->isEmpty() && ($entity->is_sign == 1 || strtotime($entity->update_time) > time() - 3600)) {
            // 已签收或一小时内更新过，直接返回
            return $entity->toArray();
        }
        // 一个人一天最多查询100次
        $name = 'wuliu_' . date('Ymd') . '_' . $userID;
        $times = Cache::remember($name, function () use ($name) {
            return Cache::get($name, 0) + 1;
        }, 86400);
        if ($times > 100) {
            throw_logic_exception('查询太过频繁，请明天再试');
        }
        return $this->queryLogistics($no, $type, $entity)->toArray();
    }

    public function queryLogistics(string $number, string $type, self $entity): self
    {
        $result = WuLiuClient::kdi($number, $type);
        $entity->number = $result->number;
        $entity->type = $result->type;
        $entity->list = $result->list;
        $entity->delivery_status = $result->deliverystatus;
        $entity->is_sign = $result->issign;
        $entity->exp_name = $result->expName;
        $entity->exp_site = $result->expSite;
        $entity->exp_phone = $result->expPhone;
        $entity->courier = $result->courier;
        $entity->courier_phone = $result->courierPhone;
        $entity->take_time = $result->takeTime;
        $entity->save();
        return $entity;
    }
}